package org.StarTest;

import java.util.*;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.facebook.api.*;
import org.w3c.dom.Document;




/**
 * Servlet implementation class for Servlet: MainPageServlet
 *
 * @web.servlet
 *   name="MainPageServlet"
 *   display-name="MainPageServlet"
 *
 * @web.servlet-mapping
 *   url-pattern="/"
 *
 */

public class MainPageServlet 
	extends AbstractFacebookServlet
	implements javax.servlet.Servlet {

	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MainPageServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		FacebookRestClient facebook = getAuthenticatedFacebookClient(request, response);

	    if ( facebook != null) {
	    	if ( getFacebookInfo(request, facebook) ) {
	    		request.getRequestDispatcher("/main_page.jsp").forward(request, response);
	    	}
	    }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	   /*
	    * This method obtains some basic Facebook profile
	    * information from the logged in user who is
	    * accessing our application in the current HTTP request.
	    */
	   private boolean getFacebookInfo(HttpServletRequest request, FacebookRestClient facebook) 
	   {
	      try {

	         long userID = facebook.users_getLoggedInUser();
	         Collection<Long> users = new ArrayList<Long>();
	         users.add(userID);

	         EnumSet<ProfileField> fields = EnumSet.of (
	            com.facebook.api.ProfileField.NAME,
	            com.facebook.api.ProfileField.PIC);

	         Document d = facebook.users_getInfo(users, fields);
	         String name = 
	            d.getElementsByTagName("name").item(0).getTextContent();
	         String picture = 
	            d.getElementsByTagName("pic").item(0).getTextContent();

	         request.setAttribute("uid", userID);
	         request.setAttribute("profile_name", name);
	         request.setAttribute("profile_picture_url", picture);

	      } catch (FacebookException e) {

	         HttpSession session = request.getSession();
	         session.setAttribute("facebookSession", null);
	         return false;

	      } catch (IOException e) {

	         e.printStackTrace();
	         return false;
	      }
	      return true;
	   }
}
